const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const cors = require('koa2-cors')
const onerror = require('koa-onerror')
const koaBody = require('koa-body')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
import db from './mongodb/db.js';
import config from './config/default'
var session = require('koa-session-minimal');
var mongoStore = require('koa-mongo-session');
const jwtKoa = require('koa-jwt');      // 用于路由权限控制

const router = require('./routes/index.js')


// error handler
onerror(app)

// 处理跨域问题
app.use(cors({
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'Date'],
  maxAge: 100,
  credentials: true,
  allowMethods: ['GET', 'POST', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous'],
}));


/* jwt密钥 */
const secret = config.secret;

/* 当token验证异常时候的处理，如token过期、token错误 */
app.use((ctx, next) => {
  return next().catch((err) => {
    console.log(err);
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = {
        ok: false,
        // msg: err.originalError ? err.originalError.message : err.message
        msg: '没token还想拿数据？做梦吧！'
      }
    } else {
      throw err;
    }
  });
});

/* 路由权限控制 */
app.use(jwtKoa({ secret: secret }).unless({
  // 设置login、register接口，可以不需要认证访问
  path: [
    /^\/api\/admin\/login/,
    /^\/api\/v1\/cities/,// 定位
    /^\/api\/v1\/cities\/:id/,
    /^\/api\/v1\/pois/,

    /^\/api\/v1\/pois\/:geohash/,
    // /^\/test\/token/,
    /^((?!\/apis).)*$/   // 设置除了私有接口外的其它资源，可以不需要认证访问
  ]
}));


// 缓存
app.use(session({
  name: config.session.name,
  secret: config.session.secret,
  resave: true,
  saveUninitialized: false,
  cookie: config.session.cookie,
  store: mongoStore({
    mongo: config.url,
    expiration: 1000 * 60 * 60 * 24 * 14
  }) 
}))


// middlewares
// 处理原生的node还是koa都无法直接解析request的body
app.use(koaBody()).use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// routes
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
